package com.thingple.usb.stream;

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;

public class InputOutputProcessor extends EventAware {

    private static final String TAG = InputOutputProcessor.class.getName();

    //////////////

    public boolean initIO(UsbManager usbManager, UsbAccessory device, ProcessFunc func) {
        Log.d(TAG, "init IO");
        if (func == null) {
            return false;
        }
        onTrace("初始化I/O");
        inputBuffer = ByteBuffer.allocate(1024);
        outputBuffer = ByteBuffer.allocate(1024);
        try {
            Log.d(TAG, "打开USB设备");
            pfd = usbManager.openAccessory(device);
            if (pfd == null) {
                Exception e = new Exception("无法打开USB设备");
                onTrace(e.toString());
                onErr(e);
                return false;
            }
            Log.d(TAG, "获取到USB文件路径");
            FileDescriptor fd = pfd.getFileDescriptor();

            Log.d(TAG, "连接USB文件IO");
            os = new FileOutputStream(fd);
            is = new FileInputStream(fd);

            work = true;
            Log.d(TAG, "执行读写逻辑");
            func.handle(this);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pfd != null) {
                try {
                    Log.d(TAG, "关闭USB设备");
                    pfd.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        return true;
    }

    public interface ProcessFunc {
        void handle(InputOutputProcessor processor);
    }

    public void loop() {
        onTrace("开始I/O循环");
        int step = 0;
        boolean hasNext = true;
        while(hasNext && work) {
            delay();
            step = (step+1)%2; // 拢共两步
            if (step == 0) {
                hasNext = tx();
            } else {
                hasNext = rx();
            }
        }
        onTrace("结束I/O循环");
    }

}
